<script lang="ts" setup>
import { ref, computed, onBeforeUnmount } from "vue";
import { useStore } from "@/stores/data";
import { useRouter } from 'vue-router'
import { dialog } from '@/utils/dialog'
import SuanliDialog from '@/components/SuanliDialog.vue';

const router = useRouter()

const store = useStore();

const showSuanliDialog = ref(false);
const qrCode = ref('/assets/images/qrcode.png')
const showClearIcon = ref(false)
const isPopupVisible = ref(false)
const password2 = ref('')
const isView = ref(false)
const isView2 = ref(false)
const redColor = ref(false)
const saveDisabled = computed(
  () => !(store.forgotPassword.new_password && password2.value && store.forgotPassword.new_password === password2.value),
)
const passwordShow = computed(
  () => (store.forgotPassword.phone && store.forgotPassword.code),
)
const isSuccessModalVisible = ref(false)

// Toast 相关
const showToast = ref(false)
const toastConfig = ref({
  title: '',
  content: ''
})

// 显示提示信息
const showToastFun = (config: { title: string; content: string; type?: string }) => {
  if (!config.type) config.type = 'tishi'
  toastConfig.value = config
  showToast.value = true
  setTimeout(() => {
    showToast.value = false
  }, 3000)
}

// 联系客服
const contact = () => {
  // isPopupVisible.value = true
  showSuanliDialog.value = true;
}

// 关闭客服弹窗
const closePopup = () => {
  isPopupVisible.value = false
}

// 清除输入
const clearInput = (event: Event) => {
  const target = event.target as HTMLInputElement
  store.forgotPassword.phone = target.value
  showClearIcon.value = target.value.length > 0
}

// 清除图标点击
const clearIcon = () => {
  store.forgotPassword.phone = ''
  store.forgotPassword.code = ''
  showClearIcon.value = false
}

// 切换密码可见性
const togglePasswordVisibility = () => {
  isView.value = !isView.value
}

// 切换确认密码可见性
const toggleConfirmPasswordVisibility = () => {
  isView2.value = !isView2.value
}

// 输入监听
const onInput = () => {
  if (store.forgotPassword.new_password && password2.value) {
    redColor.value = store.forgotPassword.new_password !== password2.value
  } else {
    redColor.value = false
  }
}

// === 倒计时相关 ===
const COUNTDOWN = 60;
const remain = ref(0);           // 剩余秒数，0 表示可再次发送
let timerId: number | null = null;
const sending = ref(false);      // 发送中的瞬时状态

const canSend = computed(() => {
  // 可根据你项目需要补充更严谨的手机号校验
  // const phoneOk = !!store.forgotPassword.phone && store.forgotPassword.phone.trim().length >= 6;
  // return !sending.value && remain.value === 0 && phoneOk && !!store.register;
  return validatePhoneNumber(store.forgotPassword.phone)
});

const btnText = computed(() => {
  return remain.value > 0 ? `${remain.value}s 后重试` : "获取验证码";
});

function startCountdown() {
  remain.value = COUNTDOWN;
  if (timerId) {
    clearInterval(timerId);
    timerId = null;
  }
  timerId = window.setInterval(() => {
    if (remain.value <= 1) {
      remain.value = 0;
      if (timerId) {
        clearInterval(timerId);
        timerId = null;
      }
    } else {
      remain.value -= 1;
    }
  }, 1000);
}

onBeforeUnmount(() => {
  if (timerId) clearInterval(timerId);
  timerId = null;
});

// 验证手机号
const validatePhoneNumber = (phone: string) => {
  const regex = /^1[3456789]\d{9}$/
  return regex.test(phone)
}

// === 获取验证码 ===
const getCode = async () => {
  if (!canSend.value) return;
  try {
    sending.value = true;
    const res = await store.getCodeAct(store.forgotPassword.phone, "forgot");
    console.log(res);
    // 成功后开始倒计时
    startCountdown();
  } catch (error) {
    console.log(error);
    // 失败则允许再次点击
  } finally {
    sending.value = false;
  }
};

// === 修改密码（你原来的调用保持不变） ===
const changePassword = async () => {
  if (!validatePhoneNumber(store.forgotPassword.phone)) {
    dialog.alert({ title: '手机号不正确', message: '手机号不正确，请输入正确的手机号' })
    return
  }
  
  if (store.forgotPassword.code === '') {
    dialog.alert({ title: '验证码不能为空', message: '验证码不能为空，请输入验证码' })
    return
  }

  if (!store.forgotPassword.new_password) {
    dialog.alert({ title: '新密码不能为空', message: '新密码不能为空，请输入新密码' })
    return
  }

  if (!password2.value) {
    dialog.alert({ title: '密码不能为空', message: '密码不能为空，请输入确认密码' })
    return
  }

  if (store.forgotPassword.new_password !== password2.value) {
    dialog.alert({ title: '两次输入密码不一致', message: '两次输入密码不一致，请确认后重新输入！' })
    return
  }
  try {
    store.forgotPassword.code = store.forgotPassword.code.toString()
    await store.changePasswordAct(
      store.forgotPassword.phone,
      null,
      store.forgotPassword.new_password,
      store.forgotPassword.code
    );
  } catch (e) {
    console.log(e);
  }
};
</script>

<template>
  <!-- <div>
    <h1>找回密码</h1>

    <input
      placeholder="请输入手机号"
      type="text"
      v-model="store.forgotPassword.phone"
    />

    <button :disabled="!canSend" @click="getCode">
      {{ btnText }}
    </button>

    <input
      placeholder="请输入验证码"
      type="text"
      v-model="store.forgotPassword.code"
    />

    <input
      placeholder="请输入新密码"
      type="text"
      v-model="store.forgotPassword.new_password"
    />

    <button @click="changePassword">更改密码</button>
  </div> -->
  <div class="reset-password-page">
    <!-- Toast 提示 -->
    <div v-if="showToast" class="toast-container">
      <div class="toast-content">
        <div class="toast-header">{{ toastConfig.title }}</div>
        <div class="toast-body">{{ toastConfig.content }}</div>
      </div>
    </div>
    
    <!-- 客服弹窗 -->
    <!-- <div v-if="isPopupVisible" class="popup-overlay">
      <div class="popup-content">
        <div class="popup-header">
          <span>联系客服</span>
          <button class="close-button" @click="closePopup">×</button>
        </div>
        <div class="popup-body">
          <img :src="qrCode" alt="客服二维码" class="qr-code" />
          <p class="popup-text">保存添加客服微信</p>
        </div>
      </div>
    </div> -->
    <SuanliDialog
      v-model="showSuanliDialog"
      type="vip"
      :show-cancel="true"
    >
    </SuanliDialog>
    
    <!-- 头部导航 -->
    <div class="header">
      <button class="back-button" @click="router.back()">
        <span class="back-icon">←</span>
      </button>
      <span class="header-title">忘记密码</span>
    </div>
    
    <div class="main">
      <div class="content">
        <div class="item">
          <div class="item-title">手机号</div>
          <div class="input-block">
            <input 
              class="item-input" 
              type="number" 
              v-model="store.forgotPassword.phone" 
              placeholder="请输入手机号" 
              @input="clearInput" 
            />
            <span v-if="showClearIcon" class="clear-icon" @click="clearIcon">×</span>
          </div>
        </div>
        
        <div class="item">
          <div class="item-title">验证码</div>
          <div class="input-block">
            <input 
              class="item-input" 
              type="number" 
              v-model="store.forgotPassword.code" 
              placeholder="请输入验证码"
            />
            <button 
              class="get-code" 
              :class="{disabled: !canSend}"
              :disabled="!canSend"
              @click="getCode"
            >
              {{ btnText }}
            </button>
          </div>
        </div>
        <div class="item" v-show="passwordShow">
          <div class="item-title">新密码</div>
          <div class="input-block">
            <input
              :type="isView ? 'text' : 'password'"
              class="item-input"
              v-model="store.forgotPassword.new_password"
              placeholder="请输入密码"
              @input="onInput"
            />
            <div class="icon" :class="{ active: isView }" @click="togglePasswordVisibility"></div>
          </div>
        </div>

        <div class="item" v-show="passwordShow">
          <div class="item-title">
            <div>确认密码</div>
            <div v-show="redColor" class="error-message">你输入的两次密码不一致</div>
          </div>
          <div class="input-block">
            <input
              :type="isView2 ? 'text' : 'password'"
              class="item-input"
              :class="{ 'error-input': redColor }"
              v-model="password2"
              placeholder="请输入密码"
              @input="onInput"
            />
            <div
              class="icon"
              :class="{ active: isView2 }"
              @click="toggleConfirmPasswordVisibility"
            ></div>
          </div>
        </div>
      </div>
      
      <div class="bottom">
        <div class="contact-help">
          若验证码获取失败请联系<span class="contact-link" @click="contact">客服处理</span>
        </div>
        
        <div class="button-block">
          <button 
            class="button" 
            @click="changePassword"
          >
            确定
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.reset-password-page {
  width: 100%;
  height: 100vh;
  background: url('@/assets/images/login/bg.png') no-repeat center / cover;
  box-sizing: border-box;
  position: relative;
  display: flex;
  flex-direction: column;
  // 主内容区
  .main {
    padding: 0 20px;
    box-sizing: border-box;
    margin-top: 30px;
    flex: 1;
    display: flex;
    flex-direction: column;
    max-width: 500px;
    width: 100%;
    margin-left: auto;
    margin-right: auto;
    
    .content {
      background: #ffffff;
      border-radius: 20px;
      padding: 35px 25px;
      box-shadow: 0 10px 30px rgba(0, 108, 255, 0.1);
      animation: slideUp 0.5s ease;
      
      .item {
        margin-bottom: 25px;
        
        &-title {
          font-weight: 600;
          font-size: 15px;
          color: #00042d;
          margin-bottom: 12px;
          display: flex;
          align-items: center;
          
          // &::before {
          //   content: '';
          //   display: inline-block;
          //   width: 4px;
          //   height: 14px;
          //   background: linear-gradient(90deg, #006cff 0%, #009fff 100%);
          //   border-radius: 2px;
          //   margin-right: 8px;
          // }
        }
        
        .input-block {
          display: flex;
          align-items: center;
          width: 100%;
          height: 48px;
          padding: 0 20px;
          box-sizing: border-box;
          background: #f5f6f9;
          border-radius: 24px;
          margin-bottom: 5px;
          transition: all 0.3s ease;
          border: 1px solid transparent;
          
          &:focus-within {
            border-color: #006cff;
            box-shadow: 0 0 0 2px rgba(0, 108, 255, 0.1);
            background: #fff;
          }
          
          .item-input {
            flex: 1;
            height: 100%;
            padding: 0;
            background: transparent;
            border: none;
            outline: none;
            font-size: 15px;
            color: #333;
            
            &::placeholder {
              color: #aaa;
              transition: color 0.3s ease;
            }
            
            &:focus::placeholder {
              color: #ccc;
            }
          }
          
          .clear-icon {
            margin-left: 10px;
            cursor: pointer;
            font-size: 18px;
            color: #999;
            transition: all 0.3s ease;
            width: 18px;
            height: 18px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;

            &:hover {
              color: #333;
              background-color: #eee;
            }
          }
          
          .get-code {
            font-weight: 500;
            font-size: 14px;
            color: #006cff;
            margin-left: 10px;
            padding: 8px 15px;
            // background: linear-gradient(90deg, rgba(0, 108, 255, 0.1) 0%, rgba(0, 159, 255, 0.1) 100%);
            background: transparent;
            border: none;
            border-radius: 16px;
            cursor: pointer;
            white-space: nowrap;
            transition: all 0.3s ease;
            
            &:hover:not(.disabled) {
              // background: linear-gradient(90deg, rgba(0, 108, 255, 0.2) 0%, rgba(0, 159, 255, 0.2) 100%);
              background: transparent;
            }
            
            &.disabled {
              color: #999;
              cursor: not-allowed;
              background: #f5f5f5;
            }
          }
          .icon {
            width: 22px;
            height: 22px;
            margin-left: 10px;
            cursor: pointer;
            background: url('@/assets/images/login/m.png') no-repeat center / contain;
            transition: transform 0.3s ease;
            
            &:hover {
              transform: scale(1.1);
            }

            &.active {
              background: url('@/assets/images/login/m1.png') no-repeat center / contain;
            }
          }
        }
      }
    }
    
    .bottom {
      margin-top: auto;
      margin-bottom: 30px;
    }
    // 联系客服提示
    .contact-help {
      margin-top: 30px;
      display: flex;
      justify-content: center;
      width: 100%;
      font-weight: 400;
      font-size: 14px;
      color: #595959;
      margin-bottom: 40px;
      .contact-link {
        color: #006cff;
        cursor: pointer;
        margin-left: 4px;
        position: relative;
        transition: color 0.3s ease;
        
        &::after {
          content: '';
          position: absolute;
          bottom: -2px;
          left: 0;
          width: 100%;
          height: 1px;
          background-color: #006cff;
          transform: scaleX(0);
          transform-origin: right;
          transition: transform 0.3s ease;
        }
        
        &:hover {
          color: #0056cc;
          
          &::after {
            transform: scaleX(1);
            transform-origin: left;
          }
        }
      }
    }
    
    // 按钮区域
    .button-block {
      width: 100%;
      display: flex;
      justify-content: center;
      
      .button {
        width: 100%;
        max-width: 350px;
        height: 48px;
        background: linear-gradient(90deg, #006cff 0%, #009fff 100%);
        border-radius: 24px;
        font-weight: 600;
        font-size: 16px;
        color: #ffffff;
        border: none;
        cursor: pointer;
        transition: all 0.3s ease;
        box-shadow: 0 4px 15px rgba(0, 108, 255, 0.3);
        
        &:hover:not(:disabled) {
          transform: translateY(-2px);
          box-shadow: 0 6px 20px rgba(0, 108, 255, 0.4);
        }
        
        &:active:not(:disabled) {
          transform: translateY(0);
          box-shadow: 0 2px 10px rgba(0, 108, 255, 0.3);
        }
        
        &:disabled {
          background: linear-gradient(90deg, #8cb8e8 0%, #8cc7e8 100%);
          cursor: not-allowed;
          box-shadow: none;
        }
      }
    }
  }
  
  // Toast 提示样式
  .toast-container {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1001;
    background-color: rgba(0, 0, 0, 0.5);
    animation: fadeIn 0.3s ease;
    
    .toast-content {
      width: 85%;
      max-width: 320px;
      background: #ffffff;
      border-radius: 16px;
      overflow: hidden;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
      animation: scaleIn 0.3s ease;
      
      .toast-header {
        padding: 15px;
        font-weight: 600;
        font-size: 16px;
        background: linear-gradient(90deg, rgba(0, 108, 255, 0.05) 0%, rgba(0, 159, 255, 0.05) 100%);
        border-bottom: 1px solid #eee;
        color: #006cff;
      }
      
      .toast-body {
        padding: 20px;
        font-size: 14px;
        line-height: 1.6;
        color: #333;
      }
    }
  }
  
  // 弹窗样式
  .popup-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.6);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
    animation: fadeIn 0.3s ease;
    
    .popup-content {
      width: 85%;
      max-width: 350px;
      background: white;
      border-radius: 20px;
      overflow: hidden;
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
      animation: scaleIn 0.3s ease;
      
      .popup-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 18px 20px;
        background: linear-gradient(90deg, rgba(0, 108, 255, 0.05) 0%, rgba(0, 159, 255, 0.05) 100%);
        border-bottom: 1px solid #eee;
        
        span {
          font-weight: 600;
          font-size: 18px;
          color: #00042d;
        }
        
        .close-button {
          background: transparent;
          border: none;
          font-size: 24px;
          cursor: pointer;
          width: 30px;
          height: 30px;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 50%;
          transition: all 0.3s ease;
          
          &:hover {
            background-color: rgba(0, 0, 0, 0.05);
          }
        }
      }
      
      .popup-body {
        padding: 30px 20px;
        display: flex;
        flex-direction: column;
        align-items: center;
        
        .qr-code {
          width: 200px;
          height: 200px;
          margin-bottom: 20px;
          border-radius: 10px;
          box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
          transition: transform 0.3s ease;
          
          &:hover {
            transform: scale(1.02);
          }
        }
        
        .popup-text {
          font-size: 15px;
          color: #333;
          font-weight: 500;
        }
      }
    }
  }
}

// 动画效果
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideUp {
  from { 
    opacity: 0;
    transform: translateY(20px);
  }
  to { 
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes scaleIn {
  from { 
    opacity: 0;
    transform: scale(0.9);
  }
  to { 
    opacity: 1;
    transform: scale(1);
  }
}

// 响应式设计
@media (max-width: 480px) {
  .reset-password-page {
    .header {
      padding: 15px;
      
      .header-title {
        font-size: 16px;
      }
    }
    
    .main {
      padding: 0 15px;
      margin-top: 20px;
      
      .content {
        padding: 25px 20px;
        
        .item {
          margin-bottom: 20px;
          
          &-title {
            font-size: 14px;
            margin-bottom: 10px;
          }
          
          .input-block {
            height: 44px;
          }
        }
      }
      
      .button-block .button {
        height: 44px;
        font-size: 15px;
      }
    }
  }
}
.error-message {
  background: rgba(222, 72, 57, 0.1);
  color: #de4839;
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 12px;
  font-weight: 500;
  display: flex;
  align-items: center;
  animation: pulse 1.5s infinite;
  
  &::before {
    content: '!';
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 16px;
    height: 16px;
    background-color: #de4839;
    color: white;
    border-radius: 50%;
    margin-right: 6px;
    font-weight: bold;
    font-size: 12px;
  }
}
</style>
